package org.eerbaar.lang.runtime;

import java.util.Deque;
import java.util.LinkedList;

import org.eerbaar.lang.Expression;
import org.eerbaar.lang.HasProperties;
import org.eerbaar.lang.HasRuntime;
import org.eerbaar.lang.Values;

public class Executor {

    private final Deque<Expression> list = new LinkedList<Expression>();
    private static final Executor executor = new Executor();

    public static Executor getInstance() {
        return executor;
    }

    private Object result = Values.UNDEF;

    private Executor() {
        //
    }

    public void execute(Expression expression) {

        if (expression instanceof HasRuntime) {
            HasRuntime has = (HasRuntime) expression;
            list.push(expression);
            Runtime r = has.getRuntime();
            r.execute(this);
            result = r.getResult();
            list.pop();
        }
    }

    public Expression find(String name) {

        Expression result = null;
        for (Expression e : list) {
            if (e instanceof HasProperties) {
                HasProperties has = (HasProperties) e;
                result = has.getProperty(name);
                if (result != null) {
                    break;
                }
            }
        }
        return result;
    }

    public Object getResult() {
        return result;
    }

}
